package com.vlefen.springcloud.grpc.grpc;

import com.vlefen.springcloud.grpc.config.GRpcProperties;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.netty.NettyChannelBuilder;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class StubFactory {

    private final GRpcProperties gRpcProperties;

    public StubFactory(GRpcProperties gRpcProperties) {
        this.gRpcProperties = gRpcProperties;
    }

    public  Object createStub(Class serviceClass, GRpcType type, DiscoveryClient discoveryClient) throws Exception {
        return createStub(type.methodName(), serviceClass, discoveryClient);
    }

    private  Object createStub(String methodName, Class stubClass, DiscoveryClient discoveryClient) throws Exception {
        Method newStub = stubClass.getMethod(methodName, Channel.class);
        Field serviceNameField = stubClass.getField("SERVICE_NAME");
        Object serviceName = serviceNameField.get(null);
        NettyChannelBuilder channelBuilder = NettyChannelBuilder.forTarget(serviceName.toString());

//        channelBuilder.loadBalancerFactory()
        channelBuilder.nameResolverFactory(new NameResolverFactory(serviceName.toString(), discoveryClient));
        channelBuilder.usePlaintext();
        ManagedChannel channel = channelBuilder.build();
        return newStub.invoke(null, channel);
    }
}
